package smetana.modules.ui.form.common;

import org.apache.pivot.wtk.*;
import org.apache.pivot.wtkx.WTKX;
import smetana.modules.ui.form.AbstractPanel;
import smetana.modules.ui.listeners.ChangeListenerList;

import java.io.File;

/**
 * @author dmitry.mamonov
 */
public class SelectFilePanel extends AbstractPanel {
    Action actionSelect = new Action() {
        @Override
        public void perform() {
            final FileBrowserSheet fileBrowserSheet = new FileBrowserSheet(FileBrowserSheet.Mode.OPEN);
            fileBrowserSheet.setSelectedFile(new File("."));
            fileBrowserSheet.open(getComponent().getWindow(), new SheetCloseListener() {
                @Override
                public void sheetClosed(Sheet sheet) {
                    if (sheet.getResult()) {
                        setFile(fileBrowserSheet.getSelectedFile());
                    } else {
                        setFile(null);
                    }
                }
            });
        }
    };

    @WTKX
    PushButton buttonSelect;


    @WTKX
    TextInput fieldFileName;

    ChangeListenerList changeListeners = new ChangeListenerList();

    File file;

    @Override
    protected void init() {
        buttonSelect.setAction(actionSelect);
    }

    public ChangeListenerList getChangeListeners() {
        return changeListeners;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
        if (file==null){
            fieldFileName.setText("");
        } else {
            fieldFileName.setText(file.getPath());
        }
        changeListeners.onChange();
    }
}
